﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Com.Alipay.Domain;
using Com.Alipay.Business;
using BLL;
using WeChat.Common;
using Com.Alipay.Model;
using System.Collections.Generic;
using System.Threading;
using Newtonsoft.Json;

namespace WeChat.Common2
{
    public class AlipayOrderInfo
    {
        public LogHelper log = new LogHelper(AppDomain.CurrentDomain.BaseDirectory + "/log/log.txt");

        public AlipayHelperService serviceClient = AlipayF2FBiz.CreateClientInstance(Config.serverUrl, Config.appId, Config.merchant_private_key, Config.version,
                        Config.sign_type, Config.alipay_public_key, Config.charset);

        /// 构造支付请求数据
        /// </summary>
        /// <param name="money">订单总金额</param>
        /// <param name="out_trade_no">订单编号</param>
        /// <returns>请求数据集</returns>
        public AlipayTradePrecreateContentBuilder BuildPrecreateContent(string money, string out_trade_no)
        {
            AlipayTradePrecreateContentBuilder builder = new AlipayTradePrecreateContentBuilder();
            //收款账号
            builder.seller_id = Config.pid;
            //订单编号
            builder.out_trade_no = out_trade_no;
            //订单总金额
            builder.total_amount = money;

            //参与优惠计算的金额
            //builder.discountable_amount = "";
            //不参与优惠计算的金额
            //builder.undiscountable_amount = "";
            //订单名称
            builder.subject = Config.body;

            //自定义超时时间
            builder.time_expire = System.DateTime.Now.AddMinutes(5).ToString("yyyy-MM-dd HH:mm:ss");
            //订单描述
            builder.body = Config.attach;
            //门店编号，很重要的参数，可以用作之后的营销
            builder.store_id = "test store id";
            //操作员编号，很重要的参数，可以用作之后的营销
            builder.operator_id = "test";

            //传入商品信息详情
            List<GoodsInfo> gList = new List<GoodsInfo>();
            GoodsInfo goods = new GoodsInfo();
            goods.goods_id = "goods id";
            goods.goods_name = "goods name";
            goods.price = "0.01";
            goods.quantity = "1";
            gList.Add(goods);
            builder.goods_detail = gList;

            //系统商接入可以填此参数用作返佣
            //ExtendParams exParam = new ExtendParams();
            //exParam.sysServiceProviderId = "20880000000000";
            //builder.extendParams = exParam;
            log.WriteLine("builder" + JsonConvert.SerializeObject(builder));
          
            return builder;

        }

        /// <summary>
        /// 轮询
        /// </summary>
        /// <param name="o">订单号</param>
        public void LoopQuery(object o)
        {
            //log.WriteLine("执行轮询");
            AlipayF2FQueryResult queryResult = new AlipayF2FQueryResult();
            int count = 65;
            int interval = 3000;//毫秒
            var obj = o as MyOrderInfo;
            string out_trade_no = obj.order_no;

            for (int i = 1; i <= count; i++)
            {
                //log.WriteLine("轮询：" + i);
                Thread.Sleep(interval);
                queryResult = serviceClient.tradeQuery(out_trade_no);
                if (queryResult != null)
                {
                    if (queryResult.Status == ResultEnum.SUCCESS)
                    {
                        DoSuccessProcess(queryResult, obj.userId);
                        //log.WriteLine("轮询结束");
                        return;
                    }

                }
            }
            DoFailedProcess(queryResult);
            //log.WriteLine("轮询结束");
        }

        /// <summary>
        /// 请添加支付成功后的处理
        /// </summary>
        private void DoSuccessProcess(AlipayF2FQueryResult queryResult, string userId)
        {
            //支付成功，请更新相应单据
            log.WriteLine("扫码支付成功：外部订单号" + queryResult.response.OutTradeNo + ";用户：" + userId);
            if (AlipayAddBLL.addNativeRecord(queryResult.response, userId) > 0)
            {
                log.WriteLine("用户卡号：" + userId + " 充值：" + queryResult.response.TotalAmount + " 成功！");
            }
            else
            {

                queryResult = serviceClient.tradeQuery(queryResult.response.OutTradeNo);
                if (queryResult != null)
                {
                    if (queryResult.Status == ResultEnum.SUCCESS)
                    {
                        log.WriteLine("警告！警告！核实数据，已扫码付款，未充值到数据库！");
                    }

                }
            }
        }

        /// <summary>
        /// 请添加支付失败后的处理
        /// </summary>
        private void DoFailedProcess(AlipayF2FQueryResult queryResult)
        {
            //支付失败，撤销订单
            serviceClient.CancelAndRetry(queryResult.response.OutTradeNo);
            log.WriteLine("支付失败，撤销订单");
        }
    }
}
